import store from "@/store";

let isNotEmptyArray = (array) => {
    return array !== undefined && array !== null && array.length > 0
}

let addRoutes = (r, child) => {
    if (isNotEmptyArray(child)) {
        child.forEach(d => {
            let currentRoute = getRoute(d.path, d.component, d.meta,d);
            if (isNotEmptyArray(d)) {
                addRoutes(currentRoute, d.child);
            } else {
                if (r.children === undefined) {
                    r.children = [];
                }
                r.children.push(currentRoute);
            }
        })
    }
}

let getRoute = (path, component, meta,menuItem) => {
    if(component !== undefined && component !== null && component.indexOf("/") !== 0){
        component+= "/"+component;
    }
    return {
        name:menuItem.name,
        path: path,
        component: (component === undefined || component === null) ? () => import('@/components/MenuRouterView') : () => import('@/views' + component),
        meta: meta
    }
}

/**
 * 只有一级菜单页面的路由配置
 */
let getOnePathRoute = (path, component, meta,menuItem) => {
    return {
        path: '',
        component: () => import('@/views/index'),
        children: [
            getRoute(path, component, meta,menuItem)
        ]
    }
}

/**
 * 加载动态路由
 */
export default function loadDynamicRouter(router) {
    return new Promise((resolve, reject) => {
        store.dispatch("GetMenus").then((menuData) => {
            try {
                let routes = [];
                menuData.forEach(d => {
                    if (!isNotEmptyArray(d.children)) {
                        let root = getOnePathRoute(d.path, d.component, d.meta,d);
                        routes.push(root);
                    } else {
                        let root = getRoute(d.path, d.component, d.meta,d);
                        root.component = () => import('@/views/index');
                        addRoutes(root, d.children)
                        routes.push(root);
                    }
                })
                router.addRoutes(routes);
                resolve(true);
            } catch (e) {
                console.log(e)
                reject(false);
            }
        }).catch(reason => reject(reason));
    })

}

